<template>
  <div style="height: 10vh;background-color:#fff;padding:10px 20px;">
    <!-- 搜索区域 -->
    <el-card style="height: 100%;">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" @submit.prevent="queryForm" class="searchForm">
        <!-- 规则编号 -->
        <el-form-item label="规则编号" prop="ruleNum">
          <el-select
              v-model="searchForm.ruleNum"
              placeholder="请选择规则编号"
              filterable
              clearable
          >
            <el-option v-for="rule in ruleOptions.ruleNums" :key="rule.value" :label="rule.label" :value="rule.value" />
          </el-select>
        </el-form-item>

        <!-- 规则名称 -->
        <el-form-item label="规则名称" prop="ruleName">
          <el-select
              v-model="searchForm.ruleName"
              placeholder="请选择规则名称"
              filterable
              clearable
          >
            <el-option v-for="rule in ruleOptions.ruleNames" :key="rule.value" :label="rule.label" :value="rule.value" />
          </el-select>
        </el-form-item>

        <!-- 长租方式 -->
        <el-form-item label="长租方式" prop="rentMode">
          <el-select
              v-model="searchForm.rentMode"
              placeholder="请选择长租方式"
              filterable
              clearable
          >
            <el-option v-for="mode in rentModes" :key="mode.value" :label="mode.label" :value="mode.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="queryForm">查询</el-button>
          <el-button type="primary" @click="openDialog('create')">新建</el-button>
          <el-button
              :disabled="selectedRows.length === 0"
              :style="{ backgroundColor: selectedRows.length === 0 ? '#ffcccc' : '#ff4d4f', color: '#fff' }"
              @click="batchDelete"
          >
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40vh" @close="resetDialogForm">
    <el-form
        :model="dialogForm"
        :rules="dialogRules"
        ref="dialogFormRef"
        label-width="8vh"
        label-position="left"
        class="dialogForm"
    >
      <el-row style="display: flex; flex-direction: column; align-items: center;" >
        <el-form-item label="规则编号" prop="ruleNum">
          <el-input v-model="dialogForm.ruleNum" placeholder="请输入规则编号" />
        </el-form-item>

        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="dialogForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>

        <el-form-item label="长租方式" prop="rentMode">
          <el-select v-model="dialogForm.rentMode" placeholder="请选择长租方式" filterable>
            <el-option v-for="mode in rentModes" :key="mode.value" :label="mode.label" :value="mode.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="租金(元)" prop="rentFee">
          <el-input-number v-model="dialogForm.rentFee" :min="0" :step="10"/>
        </el-form-item>
      </el-row>
    </el-form>

    <template #footer>
      <div style="display: flex; justify-content: center; gap: 20px;">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="saving" @click="saveDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 计费规则列表和分页区域 -->
  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <!-- 表格容器 -->
    <div class="table-container">
      <el-table
          :data="ruleList"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="ruleNum" label="规则编号" align="center" />
        <el-table-column prop="ruleName" label="规则名称" align="center" />
        <el-table-column prop="rentMode" label="长租方式" align="center" />
        <el-table-column prop="rentFee" label="租金(元)" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column prop="updateTime" label="更新时间" align="center" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页容器 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { logOperation } from '@/utils/log';

// 定义后端API接口路径
const API_URL = import.meta.env.VITE_API_BASE_URL;

// 长租方式选项
const rentModes = ref([
  { label: '月租(默认为31天)', value: '月租' },
  { label: '年租(默认为365天)', value: '年租' }
]);

// 搜索表单
const searchForm = ref({
  ruleNum: '',
  ruleName: '',
  rentMode: ''
});
const searchFormRef = ref(null);

// 表格和下拉框数据
const ruleList = ref([]);
const ruleOptions = ref({
  ruleNums: [],
  ruleNames: []
});

// 分页相关
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('新建');
const dialogForm = ref({
  id: null,
  ruleNum: '',
  ruleName: '',
  rentMode: '月租', // 默认值
  rentFee: 0,
  createTime: '',
  updateTime: ''
});
const dialogFormRef = ref(null);
const dialogRules = {
  ruleNum: [{ required: true, message: '请输入规则编号', trigger: 'blur' }],
  ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  rentMode: [{ required: true, message: '请选择长租方式', trigger: 'change' }],
  rentFee: [{ required: true, message: '请输入租金', trigger: 'blur' }]
};

// 多选框相关
const selectedRows = ref([]);
const tableRef = ref(null);

// 加载状态
const saving = ref(false);

// 查询长租规则列表（支持分页）
const queryForm = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm.value,
      page: currentPage.value,
      size: pageSize.value
    };
    const { data } = await axios.get(`${API_URL}/v1/bill-long-rule/select`, { params });
    if (data.code === 2000) {
      ruleList.value = data.response || [];
      total.value = data.total || 0;
      updateOptions(data.response);
      ElMessage.success('数据加载成功');
    } else {
      ElMessage.error(`数据加载失败: ${data.response?.message || '未知错误'}`);
      ruleList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('查询错误:', error);
    ElMessage.error('请求异常');
    ruleList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 更新下拉框选项
const updateOptions = (rules) => {
  const uniqueRuleNums = new Map();
  const uniqueRuleNames = new Map();

  rules.forEach(item => {
    if (item.ruleNum) uniqueRuleNums.set(item.ruleNum, item.ruleNum);
    if (item.ruleName) uniqueRuleNames.set(item.ruleName, item.ruleName);
  });

  ruleOptions.value.ruleNums = Array.from(uniqueRuleNums, ([value, label]) => ({value, label}));
  ruleOptions.value.ruleNames = Array.from(uniqueRuleNames, ([value, label]) => ({value, label}));
};

// 重置搜索表单
const resetForm = () => {
  searchFormRef.value.resetFields();
  currentPage.value = 1; // 重置到第一页
  queryForm();
};

// 打开弹窗
const openDialog = (type, row = {}) => {
  dialogVisible.value = true;
  dialogTitle.value = type === 'create' ? '新增长租规则' : '编辑长租规则';
  dialogForm.value = type === 'create'
      ? {id: null, ruleNum: '', ruleName: '', rentMode: '月租', rentFee: 0, createTime: '', updateTime: ''}
      : {...row};
};

// 重置弹窗表单
const resetDialogForm = () => {
  dialogFormRef.value?.resetFields();
};

// 关闭弹窗
const closeDialog = () => {
  ElMessageBox.confirm('您确认要关闭本弹窗吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        dialogVisible.value = false;
      })
      .catch(() => {
      });
};

// 保存长租规则
const saveDialog = () => {
  dialogFormRef.value.validate(async (valid) => {
    if (!valid) return;
    saving.value = true;
    try {
      const {data} = await axios.post(`${API_URL}/v1/bill-long-rule/save`, dialogForm.value);
      if (data.code === 2000) {
        ElMessage.success(dialogForm.value.id ? '更新成功' : '新建成功');
        dialogVisible.value = false;
        await queryForm();
        await logOperation('长租计费规则', `${dialogForm.value.id ? '更新' : '新建'}长租计费规则 ${dialogForm.value.ruleNum} ${dialogForm.value.ruleName}`);
      } else {
        ElMessage.error(`保存失败: ${data.response?.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('保存错误:', error);
      ElMessage.error('请求异常');
    } finally {
      saving.value = false;
    }
  });
};

// 处理多选框变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 抽象出的删除方法，支持单条和批量删除
const deleteRules = async (rows) => {
  const isBatch = Array.isArray(rows);
  const count = isBatch ? rows.length : 1;
  const ids = isBatch ? rows.map(row => row.id) : [rows.id];
  const confirmMessage = isBatch
      ? `您确认要删除 ${count} 个长租规则吗?`
      : '您确认要删除此长租规则吗?';

  try {
    await ElMessageBox.confirm(confirmMessage, '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const url = isBatch ? `${API_URL}/v1/bill-long-rule/batchDelete` : `${API_URL}/v1/bill-long-rule/delete/${ids[0]}`;
    const method = isBatch ? 'post' : 'delete';
    const requestData = isBatch ? {ids} : null;

    const {data} = await axios({
      method,
      url,
      data: requestData
    });

    if (data.code === 2000) {
      ElMessage.success(isBatch ? '批量删除成功' : '删除成功');
      await queryForm();

      const logRows = isBatch ? rows : [rows];
      for (const row of logRows) {
        await logOperation('长租规则', `删除长租规则 ${row.ruleName}`);
      }

      if (isBatch) {
        selectedRows.value = [];
        tableRef.value.clearSelection();
      }
    } else {
      ElMessage.error(`删除失败: ${data.response?.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('删除错误:', error);
    ElMessage.error('请求异常');
  }
};

// 删除单个长租规则
const deleteRow = async (row) => {
  await deleteRules(row);
};

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) return;
  await deleteRules(selectedRows.value);
};

// 分页事件处理
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryForm();
};

// 初始化加载
onMounted(() => {
  queryForm();
});
</script>

<style scoped>
.searchForm :deep(.el-select) {
  width: 15vh;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px; /* 预留分页空间 */
}

/* 分页容器样式 */
.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px; /* 确保分页区域有足够高度 */
}

.dialogForm :deep(.el-input) {
  width: 20vh;
}
.dialogForm :deep(.el-select) {
  width: 20vh;
}
.dialogForm :deep(.el-input-number) {
  width: 20vh;
}
</style>